<template>
  <div class="guild-activity-manage">
    <h2>公会活动管理</h2>
    <el-table :data="activities" style="width: 100%" border>
      <el-table-column prop="id" label="活动ID" align="center"></el-table-column>
      <el-table-column prop="guildId" label="公会ID" align="center"></el-table-column>
      <el-table-column prop="activityType" label="活动类型" align="center"></el-table-column>
      <el-table-column prop="activityTime" label="活动时间" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.activityTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="description" label="活动描述" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 10px;">
      <el-button type="primary" @click="showCreateDialog">创建活动</el-button>
      <el-button @click="fetchAllActivities">查询所有活动</el-button>
      <el-input
          v-model="searchGuildId"
          placeholder="按公会ID筛选"
          style="width: 200px; margin-left: 10px"
          @keyup.enter="fetchActivitiesByGuildId"
      />
    </div>
    <!-- 新增分页组件 -->
    <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentPageChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalRecords"
    />

    <!-- 创建活动表单对话框 -->
    <el-dialog title="创建活动" v-model="dialogVisible" width="30%">
      <el-form :model="activityForm" :rules="rules">
        <el-form-item label="公会ID">
          <el-input v-model="activityForm.guildId" />
        </el-form-item>
        <el-form-item label="活动类型">
          <el-input v-model="activityForm.activityType" />
        </el-form-item>
        <el-form-item label="活动时间" prop="activityTime">
          <el-date-picker
              v-model="activityForm.activityTime"
              type="datetime"
              placeholder="选择活动时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="活动描述">
          <el-input type="textarea" v-model="activityForm.description" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑活动对话框 -->
    <el-dialog title="编辑活动" v-model="editDialogVisible" width="30%">
      <el-form :model="editActivityForm" :rules="rules">
        <el-form-item label="公会ID">
          <el-input v-model="editActivityForm.guildId" disabled />
        </el-form-item>
        <el-form-item label="活动类型">
          <el-input v-model="editActivityForm.activityType" />
        </el-form-item>
        <el-form-item label="活动时间" prop="activityTime">
          <el-date-picker
              v-model="editActivityForm.activityTime"
              type="datetime"
              placeholder="选择活动时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="活动描述">
          <el-input type="textarea" v-model="editActivityForm.description" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateActivity">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/utils/request";
import dayjs from "dayjs";

const activities = ref([]);
const loading = ref(false);
const searchGuildId = ref('');
// 新增分页相关状态
const currentPage = ref(1);
const pageSize = ref(10);
const totalRecords = ref(0);

const dialogVisible = ref(false);
const editDialogVisible = ref(false);
const isEdit = ref(false);

const activityForm = ref({
  id: null,
  guildId: '',
  activityType: '',
  activityTime: null,
  description: ''
});

const editActivityForm = ref({
  id: null,
  guildId: '',
  activityType: '',
  activityTime: null,
  description: ''
});

// 表单验证规则
const rules = {
  guildId: [{ required: true, message: '请输入公会ID', trigger: 'blur' }],
  activityType: [{ required: true, message: '请输入活动类型', trigger: 'blur' }],
  activityTime: [{ required: true, message: '请选择活动时间', trigger: 'change' }],
  description: [{ required: true, message: '请输入活动描述', trigger: 'blur' }]
};

const formatDate = (dateString) => {
  if (!dateString) return '无';
  try {
    return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
  } catch (error) {
    return '时间格式错误';
  }
};

// 获取所有活动
const fetchAllActivities = async () => {
  try {
    loading.value = true;
    const response = await request.get('/guild/activities/all', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    });
    if (response.data && response.data.records && Array.isArray(response.data.records)) {
      activities.value = response.data.records.map(activity => ({
        ...activity,
        activityTime: activity.activityTime? dayjs(activity.activityTime).format('YYYY-MM-DD HH:mm:ss') : null
      }));
      totalRecords.value = response.data.total;
    } else {
      activities.value = [];
      totalRecords.value = 0;
    }
    ElMessage.success('获取所有活动成功');
  } catch (error) {
    console.error('获取所有活动失败:', error);
    ElMessage.error('获取所有活动失败: ' + (error.response?.data?.message || error.message));
  } finally {
    loading.value = false;
  }
};

// 根据公会ID获取活动列表
const fetchActivitiesByGuildId = async () => {
  const guildId = searchGuildId.value.trim();
  if (!guildId) {
    ElMessage.warning('请输入公会ID');
    return;
  }
  try {
    loading.value = true;
    const response = await request.get(`/guild/${guildId}/activities`, {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    });
    if (response.data && response.data.records && Array.isArray(response.data.records)) {
      activities.value = response.data.records.map(activity => ({
        ...activity,
        activityTime: activity.activityTime? dayjs(activity.activityTime).format('YYYY-MM-DD HH:mm:ss') : null
      }));
      totalRecords.value = response.data.total;
    } else {
      activities.value = [];
      totalRecords.value = 0;
    }
    ElMessage.success(`获取公会ID为 ${guildId} 的活动成功`);
  } catch (error) {
    console.error('获取活动列表失败:', error);
    ElMessage.error('获取活动列表失败: ' + (error.response?.data?.message || error.message));
  } finally {
    loading.value = false;
  }
};

// 显示创建对话框
const showCreateDialog = () => {
  dialogVisible.value = true;
  isEdit.value = false;
  activityForm.value = {
    id: null,
    guildId: '',
    activityType: '',
    activityTime: dayjs().format('YYYY-MM-DD HH:mm:ss'), // 默认当前时间
    description: ''
  };
};

// 显示编辑对话框
const showEditDialog = (activity) => {
  editDialogVisible.value = true;
  isEdit.value = true;

  // 确保时间格式正确
  editActivityForm.value = {
    ...activity,
    activityTime: activity.activityTime? dayjs(activity.activityTime).format('YYYY-MM-DD HH:mm:ss') : null
  };
};

// 提交创建活动表单
const submitForm = async () => {
  try {
    // 表单验证
    if (!activityForm.value.activityTime) {
      throw new Error('请选择活动时间');
    }

    const response = await request.post('/guild/activity', activityForm.value);
    if (response.code === 200) {
      ElMessage.success('创建活动成功');
      dialogVisible.value = false;
      // 刷新当前页活动列表
      await fetchAllActivities();
    } else {
      ElMessage.error(response.message || '创建活动失败');
    }
  } catch (error) {
    console.error('创建活动出错:', error);
    ElMessage.error('网络请求失败，请检查控制台日志');
  }
};

// 提交编辑活动表单
const updateActivity = async () => {
  try {
    // 表单验证
    if (!editActivityForm.value.activityTime) {
      throw new Error('请选择活动时间');
    }

    const response = await request.put('/guild/activity', editActivityForm.value);
    if (response.code === 200) {
      ElMessage.success('更新活动成功');
      editDialogVisible.value = false;
      // 刷新当前页活动列表
      await fetchAllActivities();
    } else {
      ElMessage.error(response.message || '更新活动失败');
    }
  } catch (error) {
    console.error('更新活动出错:', error);
    ElMessage.error('网络请求失败，请检查控制台日志');
  }
};

// 删除活动
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该活动吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await request.delete(`/guild/activity/${id}`);
    if (response.code === 200) {
      ElMessage.success('删除活动成功');
      // 刷新当前页活动列表
      await fetchAllActivities();
    } else {
      ElMessage.error(response.message || '删除活动失败');
    }
  } catch (error) {
    if (error!== 'cancel') {
      ElMessage.error('删除活动出错，请检查控制台日志');
    }
  }
};

// 每页数量改变时的处理
const handlePageSizeChange = (newPageSize) => {
  pageSize.value = newPageSize;
  currentPage.value = 1;
  fetchAllActivities();
};

// 当前页码改变时的处理
const handleCurrentPageChange = (newPage) => {
  currentPage.value = newPage;
  fetchAllActivities();
};

onMounted(() => {
  fetchAllActivities();
});
</script>

<style scoped>
.guild-activity-manage {
  padding: 20px;
}
</style>